use scraper::Node;
use std::collections::HashMap;
use ego_tree::NodeRef;


pub struct YsNode<'a> {
    node: NodeRef<'a, Node>,
}
impl<'a> YsNode<'a> {
    pub fn new(node: NodeRef<'a, Node>) -> Self {
        YsNode { node }
    }

    pub fn is_text_node(&self) -> bool {
        self.node.value().is_text()
    }

    pub fn get_text(&self) -> Option<String> {
        if self.is_text_node() {
            Some(self.node.value().as_text().unwrap().text.to_string())
        } else {
            None
        }
    }

    pub fn get_tag(&self) -> Option<String> {
        match self.node.value().is_element() {
            true => Some(self.node.value().as_element().unwrap().name().to_string()),
            false => None
        }
    }

    pub fn get_attributes(&self) -> HashMap<String, String> {
        match self.node.value().is_element() {
            true => self.node.value().as_element().unwrap().attrs.iter()
                .map(|attr| (attr.0.local.to_string(), attr.1.to_string()))
                .collect(),
            false => HashMap::new()
        }
    }

    pub fn get_attribute(&self, key: &str) -> Option<String> {
        self.get_attributes().get(key).cloned()
    }

    pub fn get_children_elements(&self) -> Vec<YsNode> {
        self.node.children()
            .filter(|child| child.value().is_element())
            .map(|child| {
                YsNode::new(child)
            })
            .collect()
    }
    pub fn get_children_raw(&self) -> Vec<YsNode> {
        self.node.children().map(|child| YsNode::new(child)).collect()
    }

}
